using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using System.Xml.Linq;

namespace CurrencyConv.Core.RatesDownloader
{
	public interface IRatesParser
	{
		IList<ExchangeRate> GetExchangeRates(XDocument ratesFromWeb);
	}

	public class RatesParser : IRatesParser
	{
		public IList<ExchangeRate> GetExchangeRates(XDocument ratesFromWeb )
		{
			if(ratesFromWeb==null) return null;

			XmlReader reader = ratesFromWeb.CreateReader();

			IList<ExchangeRate> _rates = new List<ExchangeRate>();
			while (reader.Read())
			{
				if (!reader.HasAttributes) continue;
				if (reader.HasValue) continue;

				string currency = reader.GetAttribute("currency");

				if (string.IsNullOrEmpty(currency)) continue;

				string rate = reader.GetAttribute("rate");
				decimal crtRate = Decimal.Parse(rate,new CultureInfo("en-US"));

				_rates.Add(new ExchangeRate(new Money("EUR", "EUR", 1), new Money(currency, currency, 1), crtRate));
			}

			return _rates;
		}
	}
}